<template>
  <el-dialog v-bind="dialog" :visible.sync="dialog.visible" @open="dialogOpen">
    <el-form v-bind="form">
      <el-form-item prop="staffNum" label="工号:">
        <el-input v-model="form.model.staffNum" />
      </el-form-item>
      <el-form-item v-if="!form.model.staffId" prop="phone" label="手机号:">
        <el-input v-model="form.model.phone" />
      </el-form-item>
    </el-form>
    <el-button slot="footer" size="small" type="primary" @click="submit">确 认</el-button>
    <el-button slot="footer" size="small" @click="dialog.visible = false">取 消</el-button>
  </el-dialog>
</template>

<script>
import { internetApi } from '@/api/api'
import { validatePhone } from '@/utils/validate'

export default {
  props: {
    tableData: {
      type: Array,
      default: () => {}
    },
    tableUpdate: Function
  },
  data() {
    return {
      //弹窗相关的属性
      dialog: {
        visible: false,
        title: '',
        width: '90%',
        closeOnClickModal: false
      },
      //form表单相关的参数
      form: {
        ref: 'form',
        model: {
          staffId: null,
          staffNum: null,
          phone: null
        },
        labelWidth: '90px',
        size: 'small',
        rules: {
          staffNum: [
            { required: true, message: '工号不能为空', trigger: 'blur' }
            // { validator: validateStaffNum, trigger: 'blur' }
          ],
          phone: [
            { required: true, message: '手机号不能为空', trigger: 'blur' },
            { validator: validatePhone, trigger: 'blur' }
          ]
        }
      }
    }
  },

  methods: {
    //确认按钮
    submit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.form.model.staffId) {
            await this.$request(internetApi.updateStaff, this.form.model)
          } else {
            await this.$request(internetApi.addStaff, this.form.model)
          }
          this.tableUpdate(1)
          this.dialog.visible = false
        }
      })
    },
    open(row) {
      if (row) {
        //编辑
        this.dialog.title = '编辑员工'
        this.form.model.staffId = row.staffId
        this.form.model.staffNum = row.staffNum
        this.form.model.phone = null
      } else {
        //新增
        this.form.model.staffId = null
        this.form.model.staffNum = null
        this.form.model.phone = null
        this.dialog.title = '新增员工'
      }
      this.dialog.visible = true
    },
    //弹窗打开时，清除所有校验
    dialogOpen() {
      //dialog是懒加载，所以要用$nextTick
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-dialog__wrapper ::v-deep.el-dialog {
  max-width: 500px;
}
</style>
